//
//  JCMomentsVC.m
//  PYQDemo
//
//  Created by Guo.JC on 2017/9/2.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "JCMomentsVC.h"
#import "UIScrollView+YFMJRefresh.h"
#import "JCMomentsModel.h"
#import "JCGetLocation.h"
#import <CoreLocation/CoreLocation.h>
#import "JCLocation.h"
#import <Qiniu/QiniuSDK.h>
#import "MBProgressHUD/MBProgressHUD.h"
#import <YYKit/YYKit.h>
#import "SQActionSheetView.h"
#import "WSProgressHUD.h"
#import "YFSeletePhotoManager.h"
#import "YFPostTopicViewController.h"
#import "MyNavigationViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "JCMomentMessageListVC.h"
#import "YFUserDefaults.h"
#import "YFMomentApi.h"
#import "JCMessageListModel.h"
#import "YFAlertHelper.h"
#import "UIImage+YFTintColor.h"
#import "UIScrollView+YFMJRefresh.h"

#define     kInputViewMinHeight             55
#define     kReloadButtonCornerRadius       35
#define     kMessageTipLabelCornerRadius    3
#define     kMessageTipViewHeight           40
#define     kMomentHeaderBorderWidth        1.5f

@interface JCMomentsVC ()<YFSeletePhotoManagerDelegate,JCMomentViewDelegate>

//顶部消息提示
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *messageHeightConstraint;
@property (weak, nonatomic) IBOutlet UILabel *messageTipLabel;
@property (weak, nonatomic) IBOutlet JCMomentView *momentView;
@property (nonatomic, strong) NSMutableArray <JCMomentsModel *> *allNewMomentModel;     //全新
@property (nonatomic, assign) BOOL isOnReload;                  //重新加载中
@property (nonatomic, strong) NSTimer *endReloadTimer;
@property (assign, nonatomic) NSInteger pageIndex;
@property (assign, nonatomic) ShowMomentType showMomentType;
@property (weak, nonatomic) IBOutlet UIView *reloadView;
@property (weak, nonatomic) IBOutlet UIButton *reloadBtn;
/**图片管理*/
@property (nonatomic, strong) YFSeletePhotoManager *seletePhotoManager;
@property (nonatomic, strong) UIView *badgeView;

@end

@implementation JCMomentsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self refreshMomentShowType:ShowMomentTypeAll];///默认精选
    _messageHeightConstraint.constant = 0;
}

-(void)postNewTopic{
    [self postTopic:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    BOOL isNeed = [YFUserDefaults isNeedRefreshMoment];
    if (isNeed) {
        [self refreshMomentShowType:_showMomentType];
    }
}

/**
 初始化
 */
- (void)initCode{
    __weak typeof(self)weakSelf = self;
    
    _reloadBtn.layer.cornerRadius = kReloadButtonCornerRadius;
    _reloadBtn.layer.masksToBounds = YES;
    
    _messageTipLabel.layer.cornerRadius = kMessageTipLabelCornerRadius;
    _messageTipLabel.layer.masksToBounds = YES;
    
    _momentView.delegate = self;
    _momentView.requestDataBlock = ^(MomentDataSourceType requestDataType) {
        if (requestDataType == MomentDataSourceTypeRefresh) {
            [weakSelf dropRefreshData];
        }else if (requestDataType == MomentDataSourceTypeAddMore){
            [weakSelf loadMore];
        }
    };
    _momentView.clickVideoBlock = ^(NSURL *videoURL) {
        [weakSelf playVideo:videoURL];
    };
    _momentView.nameColor = [UIColor whiteColor];
    _momentView.textColor = [UIColor whiteColor];
    _momentView.headerborderWidth = kMomentHeaderBorderWidth;
    _momentView.watchMoreButtonColor = UIColorFromHex(0x999999);
    _momentView.headerLayerColor = kTWhiteText;
    _momentView.addressColor = UIColorFromHex(0x999999);
    _momentView.backgroundColor = UIColorFromHex(0x081F35);
    _momentView.separatorColor = UIColorFromHex(0x666666);
    _momentView.timeColor = UIColorFromHex(0x666666);
    _momentView.viewColor = UIColorFromHex(0x666666);
    _momentView.commentBackImage = [[UIImage imageNamed:@"find_friend_comment_list"] imageWithTintColor:kSeparationLineColor alpha:1.0];
    _momentView.headerPlaceholdImage = [UIImage imageNamed:@"defalut_headIocn"];
    _momentView.sendButtonBorderColor = UIColorFromHex(0xcccccc);
    _momentView.sendButtonBackColor = kBgThemeColor;
    _momentView.sendButtonTinColor = [UIColor whiteColor];
    
    MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)((UITableView *)[_momentView valueForKey:@"tableView"]).mj_header;
    header.lastUpdatedTimeLabel.textColor = kTWhiteText;
    header.stateLabel.textColor = kTWhiteText;
    [header setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    
    MJRefreshBackNormalFooter *footer = (MJRefreshBackNormalFooter *)((UITableView *)[_momentView valueForKey:@"tableView"]).mj_footer;
    footer.stateLabel.textColor = kTWhiteText;
    [footer setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
}

#pragma mark -- MomentView代理
- (void)didTapAction:(JCMomentView *)momentView
          actionType:(MomentTapActionType)actionType
          momentMode:(JCMomentsModel *)momentModel
           indexPath:(NSIndexPath *)indexPath
         inputString:(NSString *)inputString{
    if (actionType == MomentTapActionTypeHeaderImageView) {
        //点击头像
        [self watchUserInfo:momentModel.userID];
    }else if (actionType == MomentTapActionTypeNickNameLabel){
        //点击昵称
    }else if (actionType == MomentTapActionTypeMomentTextLabel){
        //点击文本
    }else if (actionType == MomentTapActionTypeMenuButton){
        //点击菜单
        [self popMenu:momentModel];
    }else if (actionType == MomentTapActionTypeLike){
        //点赞
        [self likeMoment:momentModel];
    }else if (actionType == MomentTapActionTypeComment){
        //点击评论
        [self commentMoment:momentModel inputString:inputString];
    }else if (actionType == MomentTapActionTypeMoreButton){
        //点击更多
    }else if (actionType == MomentTapActionTypeWatchReport){
        //点击查看运动报告
        [self watchReportModel:momentModel];
    }else if (actionType == MomentTapActionTypeReplayComment){
        //回复评论
        [self replayCommentMoment:momentModel inputString:inputString indexPath:indexPath];
    }else if (actionType == MomentTapActionTypeDeleteComment){
        //删除评论或者回复
        [self deleteCommentMoment:momentModel indexPath:indexPath];
    }else if (actionType == MomentTapActionTypeWatchOtherInfo){
        //查看他人信息
        [self watchUserInfo:inputString];
    }
}

/**
 点赞动作
 */
- (void)likeMoment:(JCMomentsModel *)momentModel{
    __weak typeof(self)weakSelf = self;
    YFMomentApi *likeApi = [YFMomentApi mommentNormalApiWithApiType:(!momentModel.isLike ? kMomentsTopicLike:kMomentsCancelTopicLike) postId:momentModel.topicID];
    [[YFNetworkingService sharedInstance] sendRequest:likeApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            ///改变数据模型，重新计算高度，刷新界面
            momentModel.isLike = !momentModel.isLike;
            [momentModel editLikeState:momentModel.isLike];
            [weakSelf.momentView likeMoment:momentModel];
        }
    }];
}

/**
 评论帖子
 */
- (void)commentMoment:(JCMomentsModel *)momentModel inputString:(NSString *)inputString{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    YFMomentApi *commentApi = [YFMomentApi commentOrResponseApiWithText:inputString postId:momentModel.topicID parentID:nil];
    [[YFNetworkingService sharedInstance] sendRequest:commentApi callback:^(BOOL success, id result, NSError *error) {
        if (success && !error) {
            [weakSelf.hud dismiss];
            NSString *responseID = [[result responseInfo] objectForKey:@"RID"];
            [weakSelf.momentView addNewCommentForMoment:momentModel
                                             responseID:responseID
                                         commentContent:inputString];
        }else{
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }
    }];
}

/**
 回复评论
 */
- (void)replayCommentMoment:(JCMomentsModel *)momentModel
                inputString:(NSString *)inputString
                  indexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    [weakSelf.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    ///回复评论
    JCMomentResponseModel *responseModel = momentModel.responseList[indexPath.row];
    YFMomentApi *responseApi = [YFMomentApi commentOrResponseApiWithText:inputString postId:responseModel.postID parentID:responseModel.responseID];
    [[YFNetworkingService sharedInstance] sendRequest:responseApi callback:^(BOOL success, id result, NSError *error) {
        if (success && !error) {
            [weakSelf.hud dismiss];
            NSString *responseID = [[result responseInfo] objectForKey:@"RID"];
            [weakSelf.momentView addNewCommentResponseForMoment:momentModel
                                                  responseModel:responseModel
                                                     responseID:responseID
                                                responseContent:inputString];
        }else{
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }
    }];
}

/**
 删除评论或者回复
 */
- (void)deleteCommentMoment:(JCMomentsModel *)momentModel
                  indexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *delete = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        YFMomentApi *deleCommentApi = [YFMomentApi deleteCommentApiWithReponseId:momentModel.responseList[indexPath.row].responseID];
        [[YFNetworkingService sharedInstance] sendRequest:deleCommentApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                [weakSelf.hud dismiss];
                [weakSelf.momentView deleteCommentResponse:momentModel
                                             responseModel:momentModel.responseList[indexPath.row]
                                                 indexPath:indexPath];
            }else {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:1];
            }
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:delete];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

/**
 帖子右上角弹出菜单:删除帖子
 */
- (void)popMenu:(JCMomentsModel *) momentModel{
    __weak typeof(self)weakSelf = self;
    BOOL isSelf = [momentModel.userID isEqualToString:[User getLastUser].userID];
    NSString *tipMessage = isSelf?@"":@"";
    NSString *buttonTitle = isSelf?@"Delete":@"Report";
    SQActionSheetView *sheetView =
    [[SQActionSheetView alloc] initWithTitle:tipMessage
                                     buttons:@[buttonTitle,@"Cancel"]
                                      colors:@[[UIColor blackColor],[UIColor blackColor]]
                                 buttonClick:^(SQActionSheetView *sheetView, NSInteger buttonIndex) {
                                     if (buttonIndex == 0) {
                                         if (isSelf) {
                                             //删除帖子
                                             [weakSelf.hud showWithMaskType:WSProgressHUDMaskTypeClear];;
                                             YFMomentApi *deleteTopicApi = [YFMomentApi mommentNormalApiWithApiType:kMomentsDeleteTopic postId:momentModel.topicID];
                                             
                                             [[YFNetworkingService sharedInstance] sendRequest:deleteTopicApi callback:^(BOOL success, id result, NSError *error) {
                                                 if (success) {
                                                     [weakSelf.hud dismiss];
                                                     JCMomentsModel *deleteModel;
                                                     for (JCMomentsModel *dataModel in weakSelf.allNewMomentModel) {
                                                         if ([dataModel.topicID isEqualToString:momentModel.topicID]) {
                                                             deleteModel = dataModel;
                                                         }
                                                     }
                                                     ///删除源数据
                                                     [weakSelf.allNewMomentModel removeObject:deleteModel];
                                                     [weakSelf.momentView deleteMoment:momentModel];
                                                 }else {
                                                     [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:1];
                                                 }
                                             }];
                                         }else{
                                             //举报
                                             [weakSelf reportAction:momentModel.topicID spotterIDType:SpotterIDTypePost];
                                         }
                                     }else if (buttonIndex == 1){
                                     }
                                 }];
    [sheetView showView];
}

/**
 查看某个用户详情
 */
- (void)watchUserInfo:(NSString *)userID{
    
}

/**
 播放朋友圈视频
 */
- (void)playVideo:(NSURL *)videoURL{
    MPMoviePlayerViewController *mPMoviePlayerViewController;
    mPMoviePlayerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
    mPMoviePlayerViewController.view.frame = self.view.bounds;
    [self presentViewController:mPMoviePlayerViewController animated:YES completion:nil];
}

/**
 查看训练报告
 */
- (void)watchReportModel:(JCMomentsModel *)model{
   
}

#pragma mark -- 数据请求
/**
 刷新朋友圈数据
 @param             type            1：精选、0：全部
 */
- (void)refreshMomentShowType:(ShowMomentType)type{
    _showMomentType = type;
    _pageIndex = 1;
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeBlack];
    //获取消息条数
    [[YFNetworkingService sharedInstance] sendRequest:[YFMomentApi messageApiWithApiType:kMomentGetMessageCount argument:nil] callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSInteger messageCount = [[[result responseObject] objectForKey:@"errDesc"] integerValue];
            weakSelf.messageHeightConstraint.constant = kMessageTipViewHeight * (messageCount == 0?0:1);
            weakSelf.messageTipLabel.text = [NSString stringWithFormat:@"%ld messages",messageCount];
            [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
                [weakSelf.view layoutIfNeeded];
            } completion:nil];
        }
    }];
    
    YFMomentApi *getTopicListApi = [YFMomentApi getTopicListApiWithPage:_pageIndex from:@(type).stringValue];
    [[YFNetworkingService sharedInstance] sendRequest:getTopicListApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            weakSelf.reloadView.hidden = YES;
            NSArray *topicModeList = [JCMomentsModel creatModelWithArray:[[result responseObject] objectForKey:@"errDesc"]
                                                           currentUserID:[User getLastUser].userID
                                                         currentUserName:[User getUseInfo].FirstName
                                                               nameColor:UIColorFromHex(0x999999)
                                                            contentColor:[UIColor whiteColor]];
            weakSelf.allNewMomentModel = topicModeList.mutableCopy;
            [weakSelf.momentView setMomentDataArray:weakSelf.allNewMomentModel dataSourceType:MomentDataSourceTypeRefresh];
            [weakSelf.hud dismiss];
        }else{
            weakSelf.reloadView.hidden = NO;
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:1];
        }
    }];
}

/**
 下拉刷新数据
 */
- (void)dropRefreshData{
    __weak typeof(self)weakSelf = self;
    //获取消息条数
    [[YFNetworkingService sharedInstance] sendRequest:[YFMomentApi messageApiWithApiType:kMomentGetMessageCount argument:nil] callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSInteger messageCount = [[[result responseObject] objectForKey:@"errDesc"] integerValue];
            weakSelf.messageHeightConstraint.constant = kMessageTipViewHeight * (messageCount == 0?0:1);
            weakSelf.messageTipLabel.text = [NSString stringWithFormat:@"%ld messages",messageCount];
            [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
                [weakSelf.view layoutIfNeeded];
            } completion:nil];
        }
    }];
    //刷新朋友圈内容
    _pageIndex = 1;
    YFMomentApi *getTopicListApi = [YFMomentApi getTopicListApiWithPage:_pageIndex from:@(_showMomentType).stringValue];
    [[YFNetworkingService sharedInstance] sendRequest:getTopicListApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            weakSelf.reloadView.hidden = YES;
            NSArray *topicModeList = [JCMomentsModel creatModelWithArray:[[result responseObject] objectForKey:@"errDesc"]
                                                           currentUserID:[User getLastUser].userID
                                                         currentUserName:[User getUseInfo].FirstName
                                                               nameColor:UIColorFromHex(0x999999)
                                                            contentColor:[UIColor whiteColor]];
            weakSelf.allNewMomentModel = topicModeList.mutableCopy;
            [weakSelf.momentView setMomentDataArray:topicModeList
                                     dataSourceType:MomentDataSourceTypeRefresh];
        }else {
            weakSelf.reloadView.hidden = NO;
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:1];
        }
    }];
}

/**
 上拉加载更多数据
 */
- (void)loadMore{
    __weak typeof(self)weakSelf = self;
    _pageIndex++;
    YFMomentApi *getTopicListApi = [YFMomentApi getTopicListApiWithPage:_pageIndex from:@(_showMomentType).stringValue];
    [[YFNetworkingService sharedInstance] sendRequest:getTopicListApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSArray *topicModeList = [JCMomentsModel creatModelWithArray:[[result responseObject] objectForKey:@"errDesc"]
                                                           currentUserID:[User getLastUser].userID
                                                         currentUserName:[User getUseInfo].FirstName
                                                               nameColor:UIColorFromHex(0x999999)
                                                            contentColor:[UIColor whiteColor]];
            if (topicModeList.count == 0) {
                weakSelf.pageIndex -= 1;
                [weakSelf.hud showString:NSLocalizedString(@"No more data", @"没有更多数据了") dimissAfterSecond:1];
            }else{
                [weakSelf.allNewMomentModel addObjectsFromArray:topicModeList];
                [weakSelf.momentView setMomentDataArray:topicModeList
                                         dataSourceType:MomentDataSourceTypeAddMore];
            }
        }else {
            weakSelf.pageIndex -= 1;
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:1];
        }
    }];
}

#pragma mark - 点击读取消息
- (IBAction)readMessageAction:(UIButton *)sender {
    _messageHeightConstraint.constant = 0;
    [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - 切换精选、最新
- (IBAction)changeMomentTypeAction:(UISegmentedControl *)sender {
    [self refreshMomentShowType:!sender.selectedSegmentIndex];
}

- (void)dealloc{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark --  发布新帖子
- (IBAction)postTopic:(UIBarButtonItem *)sender{
    [PhotoActionSheetViewController showInParentViewController:[[UIApplication sharedApplication] keyWindow].rootViewController alertType:UIAlertControllerStyleAlert animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        [self gotoSeletePhotoOrTakePhoto:btnType];
    }].isTapCoverViewDismiss = YES;
}

/**
 发布新动态：相册、相机选择
 */
- (void)gotoSeletePhotoOrTakePhoto:(kTapActionButtonType)type {
    
    if (self.seletePhotoManager != nil) {
        self.seletePhotoManager = nil;
    }
    
    YFSeletePhotoManager *seleteManager = [[YFSeletePhotoManager alloc] init];
    self.seletePhotoManager = seleteManager;
    seleteManager.delegate = self;
    [seleteManager showPickerControllerWithType:type targetVc:self];
}

- (void)seletePhotoDidFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray *)assets isOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        YFPostTopicViewController *topicVc = [[YFPostTopicViewController alloc] init];
        topicVc.seletePhotoManager = self.seletePhotoManager;
        topicVc.type = PostTopicTypeMoment;
        MyNavigationViewController *navVc = [[MyNavigationViewController alloc] initWithRootViewController:topicVc];
        topicVc.seletePhotoManager.delegate = topicVc;
        [self presentViewController:navVc animated:YES completion:nil];
    });
}

/**
 重新加载
 */
- (IBAction)reloadAction:(UIButton *)sender {
    [self refreshMomentShowType:_showMomentType];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
   
}


@end
